package com.gmcloud.common.core.utils;

import javax.servlet.ServletInputStream;
import javax.servlet.ServletRequest;
import java.io.*;
import java.nio.charset.Charset;
import java.nio.charset.StandardCharsets;

public class HttpHelper {

    private HttpHelper() {
        throw new IllegalArgumentException("static class");
    }

    public static String getBodyString(final ServletRequest request) {
        StringBuilder sb = new StringBuilder();
        try (InputStream inputStream = cloneInputStream(request.getInputStream());
             BufferedReader reader = new BufferedReader(new InputStreamReader(inputStream, StandardCharsets.UTF_8))) {
            String line;
            while ((line = reader.readLine()) != null) {
                sb.append(line);
            }
        } catch (IOException e) {
            e.printStackTrace();
        }
        return sb.toString();
    }


    /**
     * Description: 复制输入流</br>
     *
     * @param inputStream 输入流
     * @return 输入流
     */
    public static InputStream cloneInputStream(ServletInputStream inputStream) {
        ByteArrayOutputStream byteArrayOutputStream = new ByteArrayOutputStream();
        byte[] buffer = new byte[1024];
        int len;
        try {
            while ((len = inputStream.read(buffer)) > -1) {
                byteArrayOutputStream.write(buffer, 0, len);
            }
            byteArrayOutputStream.flush();
        } catch (IOException e) {
            e.printStackTrace();
        }
        return new ByteArrayInputStream(byteArrayOutputStream.toByteArray());
    }

    /**
     * 通过BufferedReader和字符编码集转换成byte数组
     *
     * @param br       输入流
     * @param encoding 编码
     * @return 字节
     * @throws IOException 异常
     */
    public static byte[] readBytes(BufferedReader br, String encoding) throws IOException {
        String str;
        StringBuilder retStr = new StringBuilder();
        while ((str = br.readLine()) != null) {
            retStr.append(str);
        }
        if (!retStr.isEmpty()) {
            return retStr.toString().getBytes(Charset.forName(encoding));
        }
        return new byte[0];
    }
}
